import os

from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template

from ix import Start_Catalogs
from ix import Start_Bookmarks

class MainHandler(webapp.RequestHandler):
  def get(self):
    catalogs = Start_Catalogs.all().order('created')
    startlists = []
    top_visited = Start_Bookmarks.all().order('-hits').fetch(20)

    for catalog in catalogs:
      startlists.append({
        'catalog':catalog.title,
        'bookmarks':Start_Bookmarks.all().filter('type =', catalog.title).fetch(10)
      })

    view_path = os.path.join(os.path.dirname(__file__), 'view/start/main.htm')
    
    view_values = {
      'top_visited':top_visited,
      'startlists' : startlists
    }
    
    self.response.out.write(template.render(view_path, view_values))

class TypeHandler(webapp.RequestHandler):
  def get(self):
    catalogs = Start_Catalogs.all().order('-created')
    view_path = os.path.join(os.path.dirname(__file__), 'view/start/catalogs.htm')
    
    view_values = {
      'catalogs' : catalogs,
    }
    
    self.response.out.write(template.render(view_path, view_values))
  
  def post(self):
    catalog = Start_Catalogs()
    
    catalog.title = self.request.get('title')
    catalog.put()
    self.redirect('/start/admin/catalogs')

class PthHandler(webapp.RequestHandler):
  def get(self):
    bookmarks = Start_Bookmarks.all().order('-created')
    catalogs = Start_Catalogs.all().order('-created')
    view_path = os.path.join(os.path.dirname(__file__), 'view/start/bookmarks.htm')
    
    view_values = {
      'bookmarks' : bookmarks,
      'catalogs' : catalogs,
    }
    
    self.response.out.write(template.render(view_path, view_values))
  
  def post(self):
    bookmark = Start_Bookmarks()
    
    bookmark.title = self.request.get('title')
    bookmark.link = self.request.get('link')
    bookmark.type = self.request.get('type')
    bookmark.hits = 0
    bookmark.put()
    self.redirect('/start/admin/bookmarks')

class OpenLinkHandler(webapp.RequestHandler):
  def get(self, key = ''):
    if(key):
      bookmark = db.get(db.Key(key))
      bookmark.hits = bookmark.hits + 1
      bookmark.put()
      self.redirect(bookmark.link)

def main():
  application = webapp.WSGIApplication([('/start', MainHandler),
                                    ('/start/', MainHandler),
                                    ('/start/admin/catalogs', TypeHandler),
                                    ('/start/admin/bookmarks', PthHandler),
                                    ('/start/go/([0-9a-zA-Z\-]+)', OpenLinkHandler)
                                    ],
                                    debug=True)
  util.run_wsgi_app(application)


if __name__ == '__main__':
  main()
